package com.lsyw.intergrate.controller;

import com.lsyw.intergrate.common.BaseResult;
import com.lsyw.intergrate.common.file.BookProperties;
import com.lsyw.intergrate.common.file.FileUtil;
import com.lsyw.intergrate.common.file.SystemTypeUtil;
import com.lsyw.intergrate.common.util.Base64Util;
import com.lsyw.intergrate.entity.common.Base64Str;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Map;
import java.util.Set;

import static com.lsyw.intergrate.common.Base64ToMultipartFile.base64Convert;

/**
 * content：文件管理
 */
@Api(tags = "文件管理")
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${type.uploadDoc}")
    private String uploadDoc;
    @Resource
    private BookProperties bookProperties;


    /**
     * base64 文件上传
     */
    @PostMapping("/upload/base64")
    @ApiOperation(value = "base64 文件上传", notes = "base64 文件上传", httpMethod = "POST")
    public BaseResult<String> uploadFile64(@RequestBody Base64Str base64Str) throws IllegalStateException, IOException {
        String str = base64Str.getStr();
        MultipartFile file = base64Convert(str);
        // 如果文件不为空，写入上传路径，进行文件上传
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();//包括扩展名
            // 文件扩展名
            String fileKzm = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (!ArrayUtils.contains(bookProperties.getUploadType(), fileKzm.toLowerCase())) {
                return BaseResult.errorResult("不支持的文件类型");
            }
            Set<PosixFilePermission> perms = FileUtil.getFilePermissions();
            String filePath = FileUtil.getFileAllPath("", fileKzm);//日期/uuid
            String parentDir = filePath.split("/")[0];
            File parentDirFile = new File(bookProperties.getUploadPath() + parentDir);
            if (!parentDirFile.exists()) {
                boolean mkdirs = parentDirFile.mkdirs();
                if (SystemTypeUtil.isLinux()) {
                    Path parentDirPath = Paths.get(bookProperties.getUploadPath() + parentDir);
                    Files.setPosixFilePermissions(parentDirPath, perms);//给文件夹加权限
                }
            }
            byte[] bytes = file.getBytes();
            Path path = Paths.get(bookProperties.getUploadPath() + filePath);//保存到磁盘中以uuid的方式
            Path write = Files.write(path, bytes);
            if (SystemTypeUtil.isLinux()) {
                Files.setPosixFilePermissions(write, perms);//给文件加权限
            }
            return BaseResult.successResult(uploadDoc+"/"+filePath);
        }
        return BaseResult.errorResult("上传失败");
    }


    /**
     * 文件上传到本地
     * 文件会自动绑定到MultipartFile中
     *
     * @param file 上传的文件
     * @return 上传成功或失败结果
     * @throws IOException           io
     * @throws IllegalStateException IllegalState
     */
    @PostMapping("/uploadFile")
    public BaseResult<String> upload(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
        // 如果文件不为空，写入上传路径，进行文件上传
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();//包括扩展名
            // 文件扩展名
            String fileKzm = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (!ArrayUtils.contains(bookProperties.getUploadType(), fileKzm.toLowerCase())) {
                return BaseResult.errorResult("不支持的文件类型");
            }
            Set<PosixFilePermission> perms = FileUtil.getFilePermissions();
            String filePath = FileUtil.getFileAllPath("", fileKzm);//日期/uuid
            String parentDir = filePath.split("/")[0];
            File parentDirFile = new File(bookProperties.getUploadPath() + parentDir);
            if (!parentDirFile.exists()) {
                boolean mkdirs = parentDirFile.mkdirs();
                if (SystemTypeUtil.isLinux()) {
                    Path parentDirPath = Paths.get(bookProperties.getUploadPath() + parentDir);
                    Files.setPosixFilePermissions(parentDirPath, perms);//给文件夹加权限
                }
            }
            byte[] bytes = file.getBytes();
            Path path = Paths.get(bookProperties.getUploadPath() + filePath);//保存到磁盘中以uuid的方式
            Path write = Files.write(path, bytes);
            if (SystemTypeUtil.isLinux()) {
                Files.setPosixFilePermissions(write, perms);//给文件加权限
            }
            return BaseResult.successResult(uploadDoc+"/"+filePath);
        }
        return BaseResult.errorResult("上传失败，文件为空！");
    }


    /**
     * 通过https下载文件，并修改名称
     *
     * @param response 返回修改后的文件
     */
    @GetMapping("/getFile")
    public void getFile(String fileUrl,String fileName, HttpServletResponse response) {
        //String fileUrl = uploadDoc + "/api/upload/" + filePath;
        try {
            URL url = new URL(fileUrl);
            int index = fileUrl.indexOf("?");//第一个问号的位置
            if (index > -1) {
                fileUrl = fileUrl.substring(0, index);
            }
            String[] split = fileUrl.split("\\.");
            // 不同文件的MimeType参考后续链接
            response.setContentType("application/x-download");//下面三行是关键代码，处理乱码问题
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1") + "." + split[split.length - 1]);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            OutputStream fos = response.getOutputStream();
            // 读取路径下面的文件
            FileCopyUtils.copy(inStream, fos);
            response.getOutputStream().flush();
            response.getOutputStream().close();
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/urlToBase64")
    public BaseResult<String> urlToBase64(@RequestBody Map<String,Object> map) {
        return BaseResult.successResult(Base64Util.imageUrlToBase64(String.valueOf(map.get("url"))));
    }


}
